package com.flow.framework.common.util.map;

import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.util.verify.VerifyUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * map工具类
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/3
 */
@Slf4j
public final class MapUtil {

    /**
     * 获取给定map的指定key的新map
     *
     * @param map      给定map
     * @param keys     指定key
     * @param callback 出错回调
     * @param <K>      key
     * @param <V>      value
     * @return
     */
    public static <K, V> Map<K, V> getValues(Map<K, V> map, List<K> keys,
                                             Function<K, CheckedException> callback) {
        Map<K, V> result = new HashMap<>(16);
        if (VerifyUtil.hasEmpty(map, keys)) {
            return result;
        }
        for (K key : keys) {
            V value = map.get(key);
            if (null != value) {
                result.put(key, value);
            } else {
                log.error("can't find key, key: {}", key);
                throw callback.apply(key);
            }
        }
        return result;
    }

    /**
     * 获取给定map的指定key的新map
     *
     * @param map  给定map
     * @param keys 指定key
     * @param <K>  key
     * @param <V>  value
     * @return
     */
    public static <K, V> Map<K, V> getValuesQuietly(Map<K, V> map, List<K> keys) {
        Map<K, V> result = new HashMap<>(16);
        if (VerifyUtil.hasEmpty(map, keys)) {
            return result;
        }
        for (K key : keys) {
            V value = map.get(key);
            if (null != value) {
                result.put(key, value);
            }
        }
        return result;
    }
}
